package routing

import "strings"

/**
 * 分组单元
 */
type Grp struct {
	Prefix  string
	Pattern map[string]string
	Host    []string
	Port    []string
	Ext     []string
	Before  FilterFunc
	After   FilterFunc
}

/**
 * 分组函数
 * @param closure func()
 * @param group Grp
 */
func (rt *Rtr) Group(closure func(), group Grp) {

	if nil == rt.groups {
		rt.groups = []Grp{}
	}

	rt.groups = append(rt.groups, group)

	closure()

	_size := rt.groupSize()

	if 1 < _size {
		rt.groups = rt.groups[0 : _size-1]
	} else {
		rt.groups = nil
	}
}

/**
 * 解析分组
 * @param r *Route
 */
func (rt *Rtr) group(r *Route) {

	for i := len(rt.groups) - 1; i >= 0; i-- {
		rt.groupHandle(rt.groups[i], r)
	}
}

/**
 * 路由分组
 * @param group Grp
 * @param r *Route
 */
func (rt *Rtr) groupHandle(group Grp, r *Route) {

	if "" != group.Prefix {
		r.path = strings.Trim(group.Prefix, "/") + "/" + r.path
	}

	if nil != group.Before {
		r.Before(group.Before)
	}

	if nil != group.After {
		r.After(group.After)
	}

	if nil != group.Pattern {
		for k, v := range group.Pattern {
			r.Pattern(k, v)
		}
	}

	if nil != group.Host {
		for _, v := range group.Host {
			r.Host(v)
		}
	}

	if nil != group.Port {
		for _, v := range group.Port {
			r.Port(v)
		}
	}

	if nil != group.Ext {
		for _, v := range group.Ext {
			r.Ext(v)
		}
	}
}

/**
 * 返回分组长度
 * @return int
 */
func (rt *Rtr) groupSize() int {
	return len(rt.groups)
}
